<template>
	<div class="bg-white px-3" style="margin: -20px;margin-top: -1rem;margin-bottom: 0 !important;">
		<el-tabs v-model="preUrl"
		@tab-click="getList()"
		>
			
			<el-tab-pane label="管理员列表" name="manager">
				<div class="d-flex align-items-center">
					<el-button type="primary" size="mini"
					@click="openDialog('manager')">添加管理员</el-button>
					<div class="ml-auto d-flex">
						<el-input 
						v-model="keyword" 
						placeholder="请输入用户名"
						size="mini"
						style="width: 200px;"></el-input>
						<el-button type="info"
						class="ml-2"
						@click="getList(openMultiPage = true, 'manager')"
						size="mini">搜索</el-button>
					</div>
				</div>
				<el-table border class="mt-3" :data="managerList" style="width: 100%">
					<el-table-column label="用户头像" align="center">
						<template slot-scope="scope">
							<el-avatar 
							size="medium"
							:src="scope.row.avatar"></el-avatar>
						</template>
					</el-table-column>
					<el-table-column label="用户名" 
					align="center" prop="username">
					</el-table-column>
					<el-table-column
					prop="email" label="所属用户组" align="center" >
						<template slot-scope="scope">
							{{scope.row.role.name}}
						</template>
					</el-table-column>
					<el-table-column label="状态" align="center">
						<template slot-scope="scope">
							<el-button :type="scope.row.status ? 'success' : 'danger'" size="mini" plain
							@click="changeStatus(scope.row)">
								{{scope.row.status ? '启用' : '禁用'}}
							</el-button>
						</template>
					</el-table-column>
					
					<el-table-column label="操作" width="150">
						<template slot-scope="scope">
							<el-button type="text" size="mini"
							@click="openDialog('manager', scope.row)"
							>修改</el-button>
							<el-button type="text" size="mini"
							@click="deleteItem(scope.row)"
							>
								删除
							</el-button>
						</template>
					</el-table-column>
				</el-table>
			</el-tab-pane>
			<el-tab-pane label="角色管理" name="role">
				<div class="d-flex align-items-center">
					<el-button type="primary" size="mini"
					v-auth="'添加角色'"
					@click="openDialog('role')">添加角色</el-button>
				</div>
				<el-table border class="mt-3" :data="roleList" style="width: 100%">
					<el-table-column label="角色名称" 
					align="center" prop="name">
					</el-table-column>
					<el-table-column label="描述"
					align="center" prop="desc">
					</el-table-column>
					<el-table-column label="状态" align="center">
						<template slot-scope="scope">
							<el-switch v-model="scope.row.status"
							:active-value="1" :inactive-value="0"
							@change="changeStatus(scope.row, isSwitch = true)"></el-switch>
						</template>
					</el-table-column>
					
					<el-table-column label="操作" width="250">
						<template slot-scope="scope">
							<el-button type="text" size="mini"
							@click="openDialog('role', scope.row)">
								修改
							</el-button>
							<el-button type="text" size="mini"
							@click="openDrawer(scope.row)">
								配置权限
							</el-button>
							<el-button type="text" size="mini"
							@click="deleteItem(scope.row)">
								删除
							</el-button>
						</template>
					</el-table-column>
				</el-table>
			</el-tab-pane>
			<el-tab-pane label="权限管理" name="rule">
				<div class="d-flex align-items-center">
					<el-button type="primary" size="mini"
					v-auth="'添加规则'"
					@click="openDialog('rule')">添加顶级权限</el-button>
				</div>
				<el-tree :data="ruleList" :props="defaultProps" @node-click="handleNodeClick"
				default-expand-all
				:expand-on-click-node="false">
					<span class="custom-tree-node" slot-scope="{ node, data }">
							<div>
								<span class="mr-2 text-muted"
								v-if="data.menu"
								:class="data.icon ? data.icon : 'el-icon-star-off'">
								</span>
								<small v-else
								class="mr-2 text-muted">{{data.method}}</small>
								<span>{{ data.name }}</span>
								<span v-if="data.menu" class="badge ml-2">
									前端路径: {{data.frontpath}}
								</span>
								<span v-else class="badge badge-secondary ml-2">
									接口权限: {{data.condition}}
								</span>
							</div>
					        
					        <span>
								<el-button type="text" size="mini" plain
								@click="changeStatus(data)">
									{{data.status ? '启用' : '禁用'}}
								</el-button>
								<el-button type="text" size="mini"
								@click="openDialog('rule', data.id)"
								v-auth="'添加规则'">增加</el-button>
								<el-button type="text" size="mini"
								@click="openDialog('rule', data)">修改</el-button>
								<el-button type="text" size="mini"
								@click="deleteItem(data)">删除</el-button>
					        </span>
					      </span>
				</el-tree>
			</el-tab-pane>
			
		</el-tabs>
		
		<div style="height: 60px;"></div>
		<el-footer 
		class="d-flex border-top align-items-center px-0 position-fixed bg-white"
		v-if="preUrl != 'rule'"
		style="bottom: 0;left: 200px;right: 0;z-index: 10;">
			<div class="px-2" style="flex: 1;">
				<el-pagination
				 @size-change="handleSizeChange" 
				 @current-change="handleCurrentChange" 
				 :current-page="pageArr[preUrl].current"
				 :page-sizes="pageArr[preUrl].sizes" 
				 :page-size="pageArr[preUrl].size" 
				 layout="total, sizes, prev, pager, next, jumper" 
				 :total="pageArr[preUrl].total">
				</el-pagination>
			</div>
		</el-footer>
		
		<!-- 添加管理员model -->
		<el-dialog :title="getDialogTitle" :visible.sync="dialogVisible"
		width="70%"
		:before-close="handleClose">
			
			<!-- 添加管理员 -->
			<el-form :model="form.manager" label-width="80px"
			v-if="preUrl === 'manager'">
				
				<el-form-item label="用户名" prop="username">
					<el-col :span="6">
						<el-input v-model="form.manager.username" 
						placeholder="用户名" size="mini"
						></el-input>
					</el-col>
				</el-form-item>
				<el-form-item label="密码" prop="password">
					<el-col :span="6">
						<el-input v-model="form.manager.password" 
						type="password"
						placeholder="密码" size="mini"></el-input>
					</el-col>
				</el-form-item>
				<el-form-item label="头像" >
					<div>
						<span v-if="!form.manager.avatar" class="btn btn-light border mr-2"
						@click="chooseImage">
							<i class="el-icon-plus"></i>
						</span>
						<img v-else class=" rounded" :src="form.manager.avatar" 
						style="width: 80px;cursor: pointer;" 
						@click="chooseImage"/>
					</div>
				</el-form-item>
				<el-form-item label="所属角色" >
					<el-col :span="6">
						<el-select v-model="form.manager.role_id" placeholder="请选择所属角色" size="mini">
							<el-option label="== 请选择 ==" value=""></el-option>
							<el-option key="1" :label="item.name" :value="item.id"
							v-for="(item, index) in roleOptions" :key="index">
								
							</el-option>
						</el-select>
					</el-col>
				</el-form-item>
				<el-form-item label="状态" >
					<el-switch v-model="form.manager.status"
					:active-value="1" :inactive-value="0"></el-switch>
				</el-form-item>
			</el-form>
			
			<!-- 添加或者修改角色form -->
			<el-form ref="form" :model="form.role" label-width="80px"
			v-if="preUrl === 'role'">
				
				<el-form-item label="角色名称" prop="name">
					<el-col :span="6">
						<el-input v-model="form.role.name" 
						placeholder="角色名称" size="mini"
						></el-input>
					</el-col>
				</el-form-item>
				<el-form-item label="角色描述" prop="desc">
					<el-col :span="12">
						<el-input v-model="form.role.desc" 
						type="textarea"
						placeholder="角色描述" size="mini"></el-input>
					</el-col>
				</el-form-item>
				<el-form-item label="状态" >
					<el-switch v-model="form.role.status"
					:active-value="1" :inactive-value="0"></el-switch>
				</el-form-item>
			</el-form>
			
			<!-- 添加或者修改权限(规则) -->
			<el-form :model="form.rule" label-width="110px"
			v-if="preUrl === 'rule'">
				<el-form-item label="上级规则" >
					<el-col :span="6">
						<el-select v-model="form.rule.rule_id" 
						placeholder="请选择上级规则" size="mini">
							<el-option label="顶级规则" :value="0"></el-option>
							<el-option key="1" :label="item | tree" :value="item.id"
							v-for="(item, index) in ruleOptions" :key="index">
								
							</el-option>
						</el-select>
					</el-col>
				</el-form-item>
				<el-form-item label="菜单/规则" >
					<el-radio-group v-model="form.rule.menu" size="mini">
						<el-radio :label="1">菜单</el-radio>
						<el-radio :label="0">规则</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item label="名称" >
					<el-col :span="12">
						<el-input v-model="form.rule.name" 
						placeholder="名称" size="mini"
						></el-input>
					</el-col>
				</el-form-item>
				<el-form-item label="图标" 
				v-if="form.rule.menu">
					<el-col :span="12">
						<el-input v-model="form.rule.icon" 
						placeholder="图标" size="mini"
						></el-input>
					</el-col>
				</el-form-item>
				<el-form-item label="前端路由路径" 
				v-if="form.rule.menu && form.rule.rule_id > 0">
					<el-col :span="12">
						<el-input v-model="form.rule.frontpath" 
						placeholder="前端路由路径" size="mini"
						></el-input>
					</el-col>
				</el-form-item>
				<el-form-item label="前端路由别名" 
				v-if="form.rule.menu">
					<el-col :span="12">
						<el-input v-model="form.rule.desc" 
						placeholder="前端路由别名" size="mini"
						></el-input>
					</el-col>
				</el-form-item>
				<el-form-item label="controller方法" 
				v-if="!form.rule.menu">
					<el-col :span="12">
						<el-input v-model="form.rule.condition" 
						placeholder="控制器方法" size="mini"
						></el-input>
					</el-col>
				</el-form-item>
				<el-form-item label="排序"
				>
					<el-col :span="12">
						<el-input-number v-model="form.rule.order" size="mini"  label="排序"></el-input-number>
					</el-col>
				</el-form-item>
				<el-form-item label="请求方式" 
				v-if="!form.rule.menu">
					<el-col :span="6">
						<el-select v-model="form.rule.method" 
						placeholder="请求方式" size="mini">
							<el-option label="== 请选择 ==" value=""></el-option>
							<el-option label="GET" value="GET"></el-option>
							<el-option label="POST" value="POST"></el-option>
							<el-option label="PUT" value="PUT"></el-option>
							<el-option label="DELETE" value="DELETE"></el-option>
						</el-select>
					</el-col>
				</el-form-item>
				<el-form-item label="状态" >
					<el-radio-group v-model="form.rule.status" size="mini">
						<el-radio :label="1" border>启用</el-radio>
						<el-radio :label="0" border>禁用</el-radio>
					</el-radio-group>
				</el-form-item>
				
				
				
			</el-form>
			
			<span slot="footer" class="dialog-footer">
				<el-button @click="dialogVisible = false">取 消</el-button>
				<el-button type="primary" @click="submit">确 定</el-button>
			</span>
		</el-dialog>
		
		<!-- 配置权限抽屉 -->
		<el-drawer
			title="配置权限"
			:visible.sync="drawer"
			:direction="direction"
			size="40%"
			:before-close="handleClose">
		
			<div style="position: absolute;top: 52px;left: 0;right: 0;bottom: 0;">
				<div style="position: absolute;top: 0;right: 0;left: 0;bottom: 60px;overflow-y: auto;">
					<el-tree
					  :data="ruleList"
					  show-checkbox
					  node-key="id"
					  default-expand-all
					  :default-checked-keys="checkedKeys"
					  :check-strictly="true"
					  @check="check"
					  :props="defaultProps">
					</el-tree>
				</div>
				<div style="height: 60px;position: absolute;bottom: 0;right: 0;left: 0;"
				class="border d-flex align-items-center bg-white">
					<el-button class="ml-2" @click="drawer = false">取消</el-button>
					<el-button type="primary" @click="submitRules">确定</el-button>
				</div>
			</div>
			
		</el-drawer>
	</div>
</template>

<script>
	import common from "@/common/mixins/common.js";
	
	export default {
		
		mixins:[common],
		inject:['layout', 'app'],
		
		created() {
			console.log('子组件created')
			this.getList()
		},
		
		filters: {
			tree(item) {
				if(item.level == 0) return item.name
				let str = ''
				for (let i = 0; i < item.level; i++) {
					str += i == 0 ? '|--' : '--'
				}
				return str + item.name
			}
		},
		
		data() {
			return {
				drawerId: 0,
				checkedKeys:[],
				
				drawer: false,
				direction: 'rtl',
				
				openMultiPage: true,
				pageKey: 'manager',
				pageArr: {
					manager: {
						current: 1,
						sizes: [10,50,100,200],
						size: 10,
						total: 0
					},
					role: {
						current: 1,
						sizes: [10,50,100,200],
						size: 10,
						total: 0
					},
					rule: {
						current: 1,
						sizes: [10,50,100,200],
						size: 10,
						total: 0
					}
				},
				
				//角色选项
				roleOptions: [],
				//权限选项
				ruleOptions: [],
				
				//表单
				form: {
					manager: {
						username: '',
						password: '',
						avatar: '',
						role_id: '',
						status: 1
					},
					role: {
						name: '',
						desc: '',
						status: 1
					},
					rule: {
						menu: 0,
						rule_id: "",
						name: '',
						status: 1,
						frontpath: '',
						desc: '',
						condition: '',
						icon:'',
						method: '',
						order: 50
					}
				},
				
				//dialogId
				dialogId: 0,
				//
				dialogType: 'manager',
				
				//是否显示添加管理员model
				dialogVisible: false,
				
				//搜索管理员，管理员名称
				keyword: '',
				
				preUrl: 'manager',
				
				managerList: [],
				
				roleList: [],
				
				ruleList: [],
				
				defaultProps: {
					children: 'child',
					label: 'name'
				}
			}
		},
	
		
		computed: {
			getDialogTitle() {
				let action = '新增'
				if(this.dialogId != 0) {
					action = '修改'
				}
				let title = ''
				if(this.dialogType === 'manager') {
					title = '管理员'
				} else if(this.dialogType === 'role') {
					title = '角色'
				}
				return action + title
			}
		},
		
		methods: {
			//提交权限
			submitRules() {
				this.layout.showLoading()
				this.axios.post('/admin/role/set_rules', {
					id: this.drawerId,
					rule_ids: this.checkedKeys
				}, {token: true}).then(res => {
					this.drawer = false
					this.getList()
					this.$message({
						message: '恭喜你，修改权限成功',
						type: 'success'
					});
					this.layout.hideLoading()
				}).catch(err => {
					this.layout.hideLoading()
				})
			},
			//权限树check事件
			check(...e) {
				this.checkedKeys = e[1].checkedKeys
			},
			
			//打开抽屉
			openDrawer(item) {
				this.layout.showLoading()
				
				//请求权限列表
				this.axios.get('/admin/rule/1',{token: true})
					.then(res => {
						this.drawer = true
						this.ruleList = res.data.data.list
						this.checkedKeys = item.rules.map(v => v.id)
						this.drawerId = item.id
						this.layout.hideLoading()
					}).catch(err => {
						this.layout.hideLoading()
					})
			},
			
			//pageArr初始化
			initPageArr() {
				this.pageArr['manager'] = {
					current: 1,
					sizes: [10,50,100,200],
					size: 10,
					total: 0
				}
				this.pageArr['role'] = {
					current: 1,
					sizes: [10,50,100,200],
					size: 10,
					total: 0
				}
			},
			
			//提交form
			submit() {
				this.addOrEdit(this.form[this.preUrl], this.dialogId)
				this.dialogVisible = false
			},
			
			//选择图片
			chooseImage() {
				this.app.showImageModel((res) => {
					this.form.manager.avatar = res[0].url
				}, 1)
			},
			
			//打开添加model
			openDialog(type, item = false) {
				//确认类型
				this.dialogType = type
				//初始化表单
				if(type === 'manager') {
					if(!item) {
						this.form.manager = {
							username: '',
							password: '',
							avatar: '',
							role_id: '',
							status: 1
						}
						this.dialogId = 0
					} else {
						this.form.manager = {...item}
						this.dialogId = item.id
					}
				} else if (type === 'role') {
					if(!item) {
						this.form.role = {
							name: '',
							desc: '',
							status: 1
						}
						this.dialogId = 0
					} else {
						this.form.role = {...item}
						this.dialogId = item.id
					}
				} else if (type === 'rule') {
					if (!item || typeof item === 'number') {
						this.form.rule = {
							menu: 0,
							rule_id: 0,
							name: '',
							status: 1,
							frontpath: '',
							desc: '',
							condition: '',
							icon:'',
							method: 'GET',
							order: 50
						}
						if (typeof item === 'number') {
							this.form.rule.rule_id = item
						}
						this.dialogId = 0
					} else {
						this.form.rule = {...item}
						this.dialogId = item.id
					}
				}
				
				//显示弹出层
				this.dialogVisible = true
			},
			
			// model关闭之前
			handleClose(done) {
				this.$confirm('确认关闭？')
					.then(_ => {
						done();
					})
					.catch(_ => {})
			},
			
			//重写getListResult
			getListResult(e) {
				
				if(this.preUrl === 'manager') {
					this.managerList = e.list
					this.roleOptions = e.role
				} else if (this.preUrl === 'role') {
					this.roleList = e.list
				} else if (this.preUrl === 'rule') {
					this.ruleList = e.list
					this.ruleOptions = e.rules
				}
			},
			
			//重写getListUrl
			getListUrl() {
				if (this.preUrl === 'manager') {
					return `/admin/${this.preUrl}/${this.pageArr[this.preUrl].current}?limit=${this.page.size}&keyword=${this.keyword}`
				}
				return `/admin/${this.preUrl}/${this.pageArr[this.preUrl].current}?limit=${this.page.size}`
			},
			
			handleNodeClick(data) {
				console.log(data);
			},

			//修改
			// edit(data) {
			// 	data.editStatus = !data.editStatus
			// },
			
			//删除
			// remove(node, data) {
			// 	this.$confirm('此操作将删除该分类, 是否继续?', '提示', {
			// 		confirmButtonText: '删除',
			// 		cancelButtonText: '取消',
			// 		type: 'warning'
			// 	}).then(() => {
			// 		let parent = node.parent
			// 		let children = parent.data.children || parent.data
			// 		let index = children.findIndex(v => {
			// 			return v.id === data.id
			// 		})
			// 		children.splice(index, 1)
			// 		this.$message({
			// 		type: 'success',
			// 		message: '删除成功!'
			// 		});
			// 	}).catch(() => {
			// 		this.$message({
			// 		type: 'info',
			// 		message: '已取消删除'
			// 		});
			// 	});
			// },
			
			//增加子分类
			// append(data) {
			// 	let newObj = {
			// 		id: 100,
			// 		label: '新分类',
			// 		status: 1,
			// 		editStatus: true,
			// 		children: []
			// 	}
			// 	data.children.push(newObj)
			// },
			
			//node拖拽结束
			// nodeDrop(...options) {
			// 	console.log(options)
			// },
		}
	}
</script>

<style>
</style>
